package api;
//注册的接口

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import comment.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = 200;
        int data = -1; //受影响的行数
        String msg = "未知参数";

        //得到并验证前端的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(!StrUtil.isBlank(username) && !StrUtil.isBlank(password)){
            //进行注册操作
            Connection connection = DBUtil.getConnection();
            String sql = "insert into userinfo(username,password) values(?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2, MD5.create().digestHex(password));
            data = statement.executeUpdate();
            msg = "";
            DBUtil.close(null,statement,connection);
        }
        else {
            msg = "参数错误！";
        }

        //返回给前端
        resp.setContentType(ApplicationVariable.APPLICATION_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
